package cunjian;

import until.DBUtil;

import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.util.UUID;

public class DepositPanel extends JPanel {
    private JTextField phoneField;
    private JComboBox<String> sizeBox;
    private JTextField codeField;

    public DepositPanel() {
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        JPanel contentPanel = new JPanel(new GridBagLayout());
        contentPanel.setBackground(Color.WHITE);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(20, 40, 20, 40);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel titleLabel = new JLabel("扫码存件", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 30));
        gbc.gridwidth = 2;
        gbc.gridx = 0;
        gbc.gridy = 0;
        contentPanel.add(titleLabel, gbc);

        gbc.gridwidth = 1;
        gbc.gridy++;
        gbc.gridx = 0;
        JLabel phoneLabel = new JLabel("收件人手机号：");
        phoneLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        contentPanel.add(phoneLabel, gbc);
        phoneField = new JTextField(15);
        phoneField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        gbc.gridx = 1;
        contentPanel.add(phoneField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        JLabel sizeLabel = new JLabel("柜门尺寸选择：");
        sizeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        contentPanel.add(sizeLabel, gbc);
        sizeBox = new JComboBox<>(new String[]{"小柜", "中柜", "大柜"});
        sizeBox.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        gbc.gridx = 1;
        contentPanel.add(sizeBox, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        JLabel codeLabel = new JLabel("生成取件码：");
        codeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        contentPanel.add(codeLabel, gbc);
        codeField = new JTextField();
        codeField.setEditable(false);
        codeField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        codeField.setBackground(new Color(245, 245, 245));
        gbc.gridx = 1;
        contentPanel.add(codeField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = 2;
        JButton depositButton = new JButton("生成取件码并开箱");
        depositButton.setFocusPainted(false);
        depositButton.setFont(new Font("微软雅黑", Font.BOLD, 20));
        depositButton.setBackground(new Color(100, 149, 237));
        depositButton.setForeground(Color.WHITE);
        depositButton.setPreferredSize(new Dimension(300, 50));
        contentPanel.add(depositButton, gbc);

        add(Box.createVerticalStrut(30), BorderLayout.NORTH);
        add(contentPanel, BorderLayout.CENTER);
        add(Box.createVerticalStrut(30), BorderLayout.SOUTH);

        depositButton.addActionListener(e -> handleDeposit());
    }

    private void handleDeposit() {
        String phone = phoneField.getText().trim();
        String size = (String) sizeBox.getSelectedItem();

        if (phone.isEmpty() || phone.length() != 11 || !phone.matches("\\d+")) {
            JOptionPane.showMessageDialog(this, "请输入合法的11位手机号", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String pickupCode = UUID.randomUUID().toString().substring(0, 6).toUpperCase();

        try (Connection conn = DBUtil.getConnection()) {
            // 查询空闲柜门
            String sql = "SELECT id FROM lockers WHERE size = ? AND status = '空闲' LIMIT 1";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, size);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                int lockerId = rs.getInt("id");

                // 写入 parcels 表
                String insertParcel = "INSERT INTO parcels (phone, size, code, locker_id) VALUES (?, ?, ?, ?)";
                PreparedStatement insertStmt = conn.prepareStatement(insertParcel);
                insertStmt.setString(1, phone);
                insertStmt.setString(2, size);
                insertStmt.setString(3, pickupCode);
                insertStmt.setInt(4, lockerId);
                insertStmt.executeUpdate();

                // 更新 locker 状态为已占用
                String updateLocker = "UPDATE lockers SET status = '已占用' WHERE id = ?";
                PreparedStatement updateStmt = conn.prepareStatement(updateLocker);
                updateStmt.setInt(1, lockerId);
                updateStmt.executeUpdate();

                codeField.setText(pickupCode);
                JOptionPane.showMessageDialog(this,
                        "成功为 " + phone + " 存件\n柜门尺寸：" + size + "\n取件码：" + pickupCode,
                        "存件成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "暂无空闲的" + size + "可用柜门", "柜满", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库异常：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
